import pygame

from tool import *


class GameMain(object):
    """游戏主类"""

    def __init__(self):
        # pygame初始化
        pygame.init()
        # 窗口初始化
        self.screen = pygame.display.set_mode((WINDOW_SIZE.width, WINDOW_SIZE.height))  # 432*644
        # 设置窗口名
        pygame.display.set_caption("飞翔的小鸟")
        # 游戏时钟初始化
        self.clock = pygame.time.Clock()
        # 游戏精灵初始化
        self.__create_sprite()
        # 定时器--创造障碍
        pygame.time.set_timer(CREATE, 5000)

    def __create_sprite(self):
        """游戏精灵初始化"""
        # 背景精灵组
        bg = Backgroud()
        bg1 = Backgroud(is_alt=True)
        self.bg_group = pygame.sprite.Group(bg, bg1)

        # 地面
        gd = Groud()
        gd1 = Groud(is_alt=True)
        self.gd_group = pygame.sprite.Group(gd, gd1)

        # 障碍物精灵
        self.obstacle_group = pygame.sprite.Group()

        # 小鸟
        self.bird = Bird(self.screen)
        self.bird_group = pygame.sprite.Group(self.bird)

    def play_game(self):
        """开始游戏"""
        # 游戏循环
        while True:
            # 设置游戏帧数
            self.clock.tick(60)
            # 事件监听
            self.__event_handle()
            # 碰撞检测
            self.__collide()
            # 绘制图片和位置更新
            self.__update_sprite()
            # 更新界面
            pygame.display.update()

    def __event_handle(self):
        """事件监听"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                GameMain.__game_over()
            elif event.type == CREATE:
                obstacle = Obstacle()
                self.obstacle_group.add(obstacle)
        self.bird.move()

    def __collide(self):
        """碰撞检测"""
        for i in self.obstacle_group:
            __game = pygame.sprite.collide_mask(self.bird, i)
            if __game is not None:
                GameMain.__game_over()

    def __update_sprite(self):
        """绘制和更新精灵位置"""
        # 背景
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        # 障碍
        self.obstacle_group.update()
        self.obstacle_group.draw(self.screen)
        # 地面
        self.gd_group.update()
        self.gd_group.draw(self.screen)
        # 小鸟
        self.bird_group.update()
        self.bird.bird_display()

    @staticmethod
    def __game_over():
        """游戏结束"""
        pygame.quit()
        exit()


if __name__ == '__main__':
    game = GameMain()
    game.play_game()
